<template>
  <a-modal
    :title="model && model.sub ? '新增子项' : model && model.id > 0 ? '编辑' : '新增'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout" >
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="12" :md="24">
            <a-form-item label="上级">
              <a-tree-select
                show-search
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择上级"
                tree-default-expand-all
                :replaceFields="{
                  children:'childs',
                  title:'target',
                  key:'id',
                  value: 'id'
                }"
                treeNodeFilterProp="title"
                v-decorator="['parentId', {rules: [{required: true, message: '请选择上级'}]}]"
                @select="selectTree"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24">
            <a-form-item label="指标">
              <a-input
                placeholder="请输入指标"
                v-decorator="['target', {rules: [{required: true, message: '请输入指标'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="12" :md="24">
            <a-form-item label="排序">
              <a-input-number
                style="width:100%"
                placeholder="请输入排序"
                v-decorator="['sort', {rules: [{required: true, message: '请输入排序'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24">
            <a-form-item label="序号">
              <a-input
                placeholder="请输入序号"
                v-decorator="['serialNumber', {rules: [{required: true, message: '请输入序号'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="12" :md="24">
            <a-form-item label="总分">
              <a-input
                placeholder="请输入总分"
                v-decorator="['totalPoint', {rules: [{required: true, message: '请输入总分'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24" v-show="isThreeLeaf">
            <a-form-item label="是否必须">
              <a-select
                placeholder="请选择是否必须"
                v-decorator="[
                  'mustFlag',
                  {rules: [{ required: false, message: '请选择是否必须'}]}
                ]" >
                <a-select-option :value="0">否</a-select-option>
                <a-select-option :value="1">是</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" v-show="isThreeLeaf">
          <a-col :lg="24">
            <a-form-item label="说明">
              <a-textarea
                placeholder="请输入说明"
                :rows="4"
                v-decorator="['comment', {rules: [{required: false, message: '请输入说明'}]}]"></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" v-show="isThreeLeaf">
          <a-col :lg="24">
            <a-form-item label="备查资料">
              <a-textarea
                placeholder="请输入备查资料"
                :rows="4"
                v-decorator="['backUpData', {rules: [{required: false, message: '请输入备查资料'}]}]"></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" v-show="isThreeLeaf">
          <a-col :lg="24">
            <a-form-item label="考核资料">
              <a-upload
                accept=".pdf,.docx,.doc"
                name="file"
                :multiple="true"
                action="/grade-evaluation-api/minio/uploadFile"
                :headers="headers"
                :before-upload="beforeAssessmentUpload"
                v-decorator="[
                  'assessmentList',
                  {
                    rules: [{required: false}],
                    valuePropName: 'fileList',
                    getValueFromEvent: normFile,
                  },
                ]"
              >
                <a-button icon="upload">点击上传</a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 表单字段
const fields = ['id', 'parentId', 'target', 'sort', 'serialNumber', 'totalPoint', 'mustFlag', 'comment', 'backUpData', 'assessmentList']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    treeData: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    model (val) {
      if (val) {
        this.isThreeLeaf = !!val.disabled
      }
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        span: 24
      },
      wrapperCol: {
        span: 24
      }
    }
    return {
      form: this.$form.createForm(this),
      headers: {
        authorization: storage.get(ACCESS_TOKEN)
      },
      isThreeLeaf: false
    }
  },
  created () {
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    beforeAssessmentUpload (file) {
      const fileType = file.name.split('.')
      const fileFormat = fileType.slice(-1)
      const isPdfOrWord = ['doc', 'docx', 'pdf'].indexOf(fileFormat[0]) > -1
      if (!isPdfOrWord) {
        this.$message.error('只能上传word和pdf格式!')
      }
      return isPdfOrWord
    },
    normFile (e) {
      console.log('Upload img event:', e)
      if (e.file.status === 'uploading' || e.file.status === 'removed') {
        return e && e.fileList
      }
      if (e.file.status === 'done') {
        const list = []
        e.fileList.forEach(item => {
          if (item.response) {
            const { id, original, url } = item.response.data
            list.push({
              uid: id,
              name: original,
              status: 'done',
              url: url
            })
          } else {
            list.push(item)
          }
        })
        return list
      }
    },
    selectTree (value, node) {
      this.isThreeLeaf = !!node.isLeaf
    }
  }
}
</script>
